// 导入db模块
const db = require('../config/db');

const getDateTime2 = (str) => {
	let date = new Date(str);
	let YY = date.getFullYear();
	let MM = date.getMonth() + 1;
	let DD = date.getDate();
	let h = date.getHours();
	let m = date.getMinutes();
	let s = date.getSeconds();

	h = h < 10 ? '0'+h : h;
	m = m < 10 ? '0'+m : m;
	s = s < 10 ? '0'+s : s;
	return `${YY}-${MM}-${DD} ${h}:${m}:${s}`;
}


// 数据表：db_parking_record
// 停车记录类
class ParkingRecord {
    // 进场
    // 注册(车牌号码，进场时间)
    enter(vehicle_num, parking_record_enter_time) {
        return new Promise((resolve, reject) => {
            // 查询sql语句
            let sql = `select parking_record_leave_time from db_parking_record where vehicle_num='${vehicle_num}'`;
            db.query(sql)
                .then(
                    (rows) => {
                        // 长度为0 添加记录
                        if(rows.length == 0) {
                            // 添加停车记录信息
                            // 插入数据sql语句
                            let sql2 = `insert into db_parking_record(vehicle_num, parking_record_enter_time) values('${vehicle_num}','${parking_record_enter_time}')`;
                            // 返回添加数据的promise
                            return db.query(sql2)
                        }
                        // 不存在出场时间  添加记录
                        if(rows.length > 0){
                             let arr = [...rows];
                             let newArr = arr.filter(item=> {
                                if(item.parking_record_leave_time == undefined || item.parking_record_leave_time == null) {
                                    return item;
                                }
                             })
                             // 判断车辆是否重新进入停车场
                             if(newArr.length === 0) {
                                // 添加停车记录信息
                                // 插入数据sql语句
                                let sql2 = `insert into db_parking_record(vehicle_num, parking_record_enter_time) values('${vehicle_num}','${parking_record_enter_time}')`;
                                // 返回添加数据的promise
                                return db.query(sql2)
                             }
                             else {
                                resolve({
                                    code: 1,
                                    msg: "车辆仍在停车场哦~"
                                })
                             }
                        }


                    },
                    () => {
                        // 执行失败
                        reject({
                            code: -1,
                            msg: '查询车辆停车记录失败。'
                        })
                    }
                )
                .then(
                    (data) => {
                        resolve({
                            code: 200,
                            msg: '登记车辆入场信息成功。',
                            parking_record_enter_time,
                            vehicle_num
                        })
                    },
                    (err) => {
                        // console.log(err)
                        reject({
                            code: -1,
                            msg: '登记车辆入场信息失败。',
                            err
                        })
                    }
                )
        })
    }
    // 离场
    leave(vehicle_num,parking_record_leave_time){
        return new Promise((resolve, reject) => {
            // 查询sql语句
            let sql = `select * from db_parking_record where vehicle_num='${vehicle_num}'`;
            db.query(sql)
                .then(
                    (rows) => {
                        // 不存在出场时间  添加记录
                        if(rows.length > 0){
                             let arr = [...rows];
                             let newArr = arr.filter(item=> {
                                if(item.parking_record_leave_time == undefined || item.parking_record_leave_time == null) {
                                    return item;
                                }
                             })
                            //  console.log("1:",newArr)
                             // 判断车辆是当前停车记录
                             if(newArr.length == 1) {
                                     let parking_record_id = newArr[0].parking_record_id;
                                     let parking_record_enter_time = newArr[0].parking_record_enter_time;
                                      // 计算费用
                                      let startTime = new Date(parking_record_enter_time).getTime();
                                      let endTime = new Date(parking_record_leave_time).getTime();
                                      // 停车总秒数
                                      let times = (endTime - startTime ) / 1000;
                                      //console.log({times})
                                      // 计算分钟
                                      let minutes = Math.floor(times / 60);
                                      let parking_record_cost = 0;
                                      // 不超过30分钟 费用为0
                                      if(minutes < 30) {
                                        parking_record_cost = 0;
                                      }
                                      else {
                                        // 计算小时
                                        let hours = Math.floor(times / 3600);
                                        // 超过30分钟不足1小时，算1小时5元
                                        if(hours < 1) {
                                            parking_record_cost = 5;
                                        }
                                        // 超过1小时
                                        else {
                                            // 计算停了多少小时的停车费用
                                            parking_record_cost = hours * 5

                                            // 剩余分钟
                                            let m = Math.floor(times % 3600 / 60);
                                            // 超过n小时的分钟计算
                                            if(m >= 30) {
                                                parking_record_cost += (m / 60) * 5;
                                                // 如果存在小数点
                                                let str = parking_record_cost.toString()
                                                if(str.indexOf(".") > -1) {
                                                    // 保留两位小数
                                                    let index = str.indexOf(".");
                                                    let newStr = str.slice(0,index + 3);
                                                    let money = newStr - 0;
                                                    parking_record_cost = money;
                                                }
                                                
                                            }
                                        }


                                      }
                                     // 更新车辆出场信息
                                    let sql2 = `update db_parking_record set parking_record_leave_time= '${parking_record_leave_time}',parking_record_cost='${parking_record_cost}' where  parking_record_id= '${parking_record_id}'`;

                                    db.query(sql2)
                                        .then(
                                            (result) => {
                                                let data = {
                                                    code: 200,
                                                    msg: '登记车辆出场信息成功。',
                                                    parking_record_cost: parking_record_cost,
                                                    parking_record_enter_time : getDateTime2(parking_record_enter_time),
                                                    parking_record_leave_time: parking_record_leave_time,
                                                    parking_record_id: parking_record_id,
                                                    vehicle_num: vehicle_num
                                                }
                                                resolve(data)
                                            }
                                            ,
                                            (err) => {
                                                reject({
                                                    code: -1,
                                                    msg: '服务端发生异常。~~~',
                                                    err
                                                })
                                            }
                                        )
                             }
                             else {
                                resolve({
                                    code: 1,
                                    msg: "该车辆已经离场。"
                                })
                             }
                             
                        }
                        else {
                            resolve({
                                code: 404,
                                msg: "不存在该车辆的停车记录。"
                            })
                        }


                    },
                    () => {
                        // 执行失败
                        reject({
                            code: -1,
                            msg: '查询停车记录失败。'
                        })
                    }
                )
                
        })
    }
    // 所有车辆停车记录
    list(page, pageSize) {
        return new Promise((resolve, reject) => {
            //获取分页数据
            let page_num = ((parseInt(page) - 1) * parseInt(pageSize))
            let page_size = (parseInt(pageSize))
            let sql = `select * from db_parking_record limit ${page_num} , ${page_size}`;
            let sql2 = `select count(*) as total from db_parking_record`

            db.query(sql)
                .then(
                    (rows) => {
                        let data;
                        db.query(sql2)
                            .then(
                                (obj) => {
                                    data = obj
                                    resolve({
                                        code: 200,
                                        msg: '获取所有停车记录成功。',
                                        result: rows,
                                        page,
                                        pageSize,
                                        data
                                    })
                                }
                            )
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: '获取所有停车记录失败。',
                            err
                        })
                    }
                )
        })
    }
    // 用户停车记录
    userlist(vehicle_num) {
        return new Promise((resolve, reject) => {
            let sql = `select * from db_parking_record where vehicle_num = '${vehicle_num}'`;
            let sql2 = `select count(*) as total from db_parking_record where vehicle_num = '${vehicle_num}'`

            db.query(sql)
                .then(
                    (rows) => {
                        let data;
                        db.query(sql2)
                            .then(
                                (obj) => {
                                    data = obj
                                    resolve({
                                        code: 200,
                                        msg: '获取用户停车记录成功。',
                                        result: rows,
                                        data
                                    })
                                }
                            )
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: '获取用户停车记录失败。',
                            err
                        })
                    }
                )
        })
    }
    // 删除停车记录
    remove(parking_record_id) {
        return new Promise((resolve, reject) => {
            let sql = `select parking_record_id from db_parking_record where parking_record_id = '${parking_record_id}'`
            db.query(sql)
                .then(
                    (rows) => {
                        if (rows.length == 0) {
                            resolve({
                                code: 404,
                                msg: '该停车记录不存在了。'
                            })
                        }
                        else {
                            // 删除
                            let sql2 = `delete from db_parking_record where parking_record_id = '${parking_record_id}'`
                            db.query(sql2)
                                .then(
                                    (result) => {
                                        // console.log("1.0",result);
                                        if (result.affectedRows === 1) {
                                            resolve({
                                                code: 200,
                                                msg: '删除停车记录成功。'
                                            })
                                        }
                                        else {
                                            resolve({
                                                code: -1,
                                                msg: '删除停车记录失败。1111'
                                            })
                                        }
                                    },
                                    () => {
                                        reject({
                                            code: -1,
                                            msg: '删除停车记录败。2222'
                                        })
                                    }
                                )
                        }
                    },
                    (err) => {
                        reject({
                            code: -1,
                            msg: '查询停车记录失败。',
                            err
                        })
                    }
                )
        })
    }
}

// 暴露停车记录类实例
module.exports = new ParkingRecord();